<template>
	<view>
		<view class="grid-box">
			<u-form :model="form" label-width="180rpx" ref="uForm">
				<u-form-item label="名称" required>
					<u-input placeholder="请输入可回收物名称" border v-model="form.name" />
				</u-form-item>
				<u-form-item label="归属类型" v-if="form.hasTypeId == 0" required>
					<u-input v-model="form.typename" placeholder="请选择归属类型" type="select" border
						@click="typeChooseVisible = true" />
				</u-form-item>
				<!-- <u-form-item label="减碳量百分比">
					<u-input placeholder="请输入减碳量百分比" type="number" inputmode="decimal" border v-model="form.carbon"/>
				</u-form-item> -->
				<u-form-item label="排序" required>
					<u-input placeholder="请输入排序" type="number" inputmode="decimal" border v-model="form.sort" />
				</u-form-item>
				<u-form-item label="默认上门价" required>
					<u-input placeholder="请输入默认上门价" type="number" inputmode="decimal" border
						v-model="form.onsiteprice.price" />
				</u-form-item>
				<u-form-item label="是否允许修改上门价" :label-style="{'line-height': '1.4em'}">
					<u-switch v-model="form.onsiteprice.edit" size="40"></u-switch>
				</u-form-item>
				<u-form-item label="上门最低价" v-if="form.onsiteprice.edit" required>
					<u-input placeholder="请输入上门最低价" type="number" inputmode="decimal" border
						v-model="form.onsiteprice.minprice" />
				</u-form-item>
				<u-form-item label="上门最高价" v-if="form.onsiteprice.edit" required>
					<u-input placeholder="请输入上门最高价" type="number" inputmode="decimal" border
						v-model="form.onsiteprice.highprice" />
				</u-form-item>
				<u-form-item label="默认站点价" required>
					<u-input placeholder="请输入默认站点价" type="number" inputmode="decimal" border
						v-model="form.storeprice.price" />
				</u-form-item>
				<u-form-item label="是否允许修改站点价" :label-style="{'line-height': '1.4em'}">
					<u-switch v-model="form.storeprice.edit" size="40"></u-switch>
				</u-form-item>
				<u-form-item label="站点最低价" v-if="form.storeprice.edit" required>
					<u-input placeholder="请输入站点最低价" type="number" inputmode="decimal" border
						v-model="form.storeprice.minprice" />
				</u-form-item>
				<u-form-item label="站点最高价" v-if="form.storeprice.edit" required>
					<u-input placeholder="请输入站点最高价" type="number" inputmode="decimal" border
						v-model="form.storeprice.highprice" />
				</u-form-item>
				<u-form-item label="预估出库价" required>
					<u-input placeholder="请输入预估出库价" type="number" inputmode="decimal" border v-model="form.packprice" />
				</u-form-item>
				<u-form-item label="计算方式" :label-style="{'line-height': '1.4em'}" required>
					<!-- <u-switch v-model="form.isweighing" size="40"></u-switch> -->
					<u-radio-group v-model="form.isweighing">
						<u-radio :name="true">
							按重量计算
						</u-radio>
						<u-radio :name="false">
							按件计算
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="按件估重(选填)" :label-style="{'line-height': '1.4em'}" v-if="!form.isweighing">
					<u-input placeholder="请输入按件估重的重量" type="number" inputmode="decimal" border
						v-model="form.estimatedweight" />
				</u-form-item>
				<u-form-item label="备注">
					<u-input placeholder="请输入备注" border v-model="form.remarks" type="textarea" />
				</u-form-item>
			</u-form>
		</view>
		<!-- 底部按钮 -->
		<view class="bottom-box">
			<view class="fixed-container">
				<view class="btn-group">
					<view class="u-flex">
						<view class="u-p-r-30 u-text-right">
							<text class="u-color-main" style="text-decoration: underline;" @click="back">返回</text>
						</view>
						<view class="u-flex-1">
							<u-button type="primary" @click="confirm">确定</u-button>
						</view>
					</view>
				</view>
			</view>
			<view class="fixed-placeholder"></view>
		</view>

		<!-- 选择目录 -->
		<u-popup v-model="typeChooseVisible" mode="bottom" length="100%">
			<view class="u-flex u-p-30">
				<view @click="typeChooseVisible = false"><text>取消</text></view>
				<view class="u-flex-1 u-text-center"><text>选择归属类型</text></view>
				<view @click="chooseType"><text class="link">确定</text></view>
			</view>
			<multi-select :options="treeData" :load-data="loadChildrenData" v-model="selected" />
		</u-popup>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';

	export default {
		data() {
			return {
				form: {
					"typeid": null,
					"id": 0,
					"name": "",
					"typename": "",
					"carbon": null,
					"pic": "",
					"sort": null,
					"packprice": null,
					"isweighing": true,
					"onsiteprice": {
						"edit": false,
						"price": null,
						"minprice": null,
						"highprice": null
					},
					"storeprice": {
						"edit": false,
						"price": null,
						"minprice": null,
						"highprice": null
					},
					"estimatedweight": null,
					"hasTypeId": 0,
				},
				typeChooseVisible: false,
				selected: {},
				treeData: [{
					name: '一级目录',
					id: 0,
					isChoose: false,
					isLeaf: false // 明确标记是否为叶子节点
				}],
			}
		},
		computed: {
			// ...mapState({
			// 	productItem: state => state.productItem
			// })
		},
		onLoad() {
			// this.form = this.productItem
		},
		methods: {
			// 自定义验证方法
			validateForm() {
				const errors = [];

				// 验证必填字段
				if (!this.form.name) {
					errors.push('请输入名称');
				}

				// if (!this.form.typename) {
				// 	errors.push('请选择归属类型');
				// }

				if (this.form.sort === null || this.form.sort === '') {
					errors.push('请输入排序');
				}

				if (this.form.onsiteprice.price === null || this.form.onsiteprice.price === '') {
					errors.push('请输入默认上门价');
				}

				if (this.form.storeprice.price === null || this.form.storeprice.price === '') {
					errors.push('请输入默认站点价');
				}

				if (this.form.packprice === null || this.form.packprice === '') {
					errors.push('请输入预估出库价');
				}

				// 根据开关状态验证动态字段
				if (this.form.onsiteprice.edit) {
					if (this.form.onsiteprice.minprice === null || this.form.onsiteprice.minprice === '') {
						errors.push('请输入上门最低价');
					}
					if (this.form.onsiteprice.highprice === null || this.form.onsiteprice.highprice === '') {
						errors.push('请输入上门最高价');
					}

					// 验证价格逻辑（可选）
					if (this.form.onsiteprice.minprice !== null && this.form.onsiteprice.highprice !== null) {
						const min = parseFloat(this.form.onsiteprice.minprice);
						const max = parseFloat(this.form.onsiteprice.highprice);
						const price = parseFloat(this.form.onsiteprice.price);

						if (min > max) {
							errors.push('上门最低价不能大于上门最高价');
						}

						if (price < min || price > max) {
							errors.push('默认上门价应在最低价和最高价之间');
						}
					}
				}

				if (this.form.storeprice.edit) {
					if (this.form.storeprice.minprice === null || this.form.storeprice.minprice === '') {
						errors.push('请输入站点最低价');
					}
					if (this.form.storeprice.highprice === null || this.form.storeprice.highprice === '') {
						errors.push('请输入站点最高价');
					}

					// 验证价格逻辑（可选）
					if (this.form.storeprice.minprice !== null && this.form.storeprice.highprice !== null) {
						const min = parseFloat(this.form.storeprice.minprice);
						const max = parseFloat(this.form.storeprice.highprice);
						const price = parseFloat(this.form.storeprice.price);

						if (min > max) {
							errors.push('站点最低价不能大于站点最高价');
						}

						if (price < min || price > max) {
							errors.push('默认站点价应在最低价和最高价之间');
						}
					}
				}

				// 验证数值格式
				const numberFields = [{
						value: this.form.sort,
						name: '排序'
					},
					{
						value: this.form.onsiteprice.price,
						name: '默认上门价'
					},
					{
						value: this.form.storeprice.price,
						name: '默认站点价'
					},
					{
						value: this.form.packprice,
						name: '预估出库价'
					}
				];

				if (this.form.onsiteprice.edit) {
					numberFields.push({
						value: this.form.onsiteprice.minprice,
						name: '上门最低价'
					}, {
						value: this.form.onsiteprice.highprice,
						name: '上门最高价'
					});
				}

				if (this.form.storeprice.edit) {
					numberFields.push({
						value: this.form.storeprice.minprice,
						name: '站点最低价'
					}, {
						value: this.form.storeprice.highprice,
						name: '站点最高价'
					});
				}

				numberFields.forEach(field => {
					if (field.value !== null && field.value !== '' && isNaN(parseFloat(field.value))) {
						errors.push(`${field.name}必须是有效数字`);
					}
				});

				return errors;
			},
			// 清理表单数据，去除null值
			cleanFormData(data) {
				const cleanedData = {};

				for (const key in data) {
					if (data[key] !== null) {
						// 如果是对象，递归处理
						if (typeof data[key] === 'object' && !Array.isArray(data[key])) {
							cleanedData[key] = this.cleanFormData(data[key]);
						} else {
							// 保留非null值
							cleanedData[key] = data[key];
						}
					}
				}

				return cleanedData;
			},
			confirm() {
				// 添加调试日志
				console.log('Confirm method triggered');

				// 执行自定义验证
				const errors = this.validateForm();
				if (errors.length > 0) {
					// 显示第一个错误信息
					this.$u.toast(errors[0]);
					return;
				}

				// 清理表单数据，去除null值
				const cleanedForm = this.cleanFormData(this.form);
				console.log('Form data:', this.form);
				this.$u.post('/Waste/Product/Create', cleanedForm).then((res) => {
					uni.showModal({
						content: '修改成功',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/admin/productList/productList'
								})
							}
						}
					});
				}).catch(err => {
					this.$u.toast('提交失败');
				})
			},
			// 选择归属类型
			chooseType() {
				this.typeChooseVisible = false
				console.log('selected', this.selected)
				this.form.typeid = this.selected.id
				this.form.typename = this.selected.name
			},
			async loadChildrenData(node) {
				try {
					const res = await this.$u.get('/Waste/type/List', {
						operatorid: this.operatorid,
						pid: node.id,
						key: node.key
					})
					return res.map(item => ({
						...item,
						// isLeaf: item.levelType === 4 // 根据业务逻辑判断是否为末级
					})).filter((cell) => cell.usestate == '已启用')
				} catch (e) {
					this.$u.toast('加载失败')
					return []
				}
			},
			back() {
				uni.navigateBack()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bottom-box {
		height: 140rpx;

		.fixed-container {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			width: 750rpx;
			padding-top: 0;
			// height: 128rpx;
			z-index: 9;
			box-shadow: 0 0 16rpx #e7e7e7;
		}

		.fixed-placeholder {
			height: 100%;
			width: 750rpx;
			margin-top: 30rpx;
		}

		.total {
			line-height: 80rpx;
			padding-left: 30rpx;
			padding-right: 30rpx;
			margin: 0;
		}

		.btn-group {
			padding: 30rpx;
		}
	}
</style>